<template>
  <div v-loading="pageLoading" class="gl_contentBox gl_heightFull">
    <el-form ref="form" class="gl_form_mini" size="medium" :model="vo" :rules="rules" label-width="120px">
      <el-divider content-position="left">选择学员</el-divider>
      <el-row>
        <el-col :xs="16" :sm="16" :md="12" :lg="6">
          <el-form-item label="学员" prop="registerStudentId">
            <!-- <el-select v-model="vo.registerStudentId" style="width: 100%;" filterable placeholder="请选择办理报名的学员">
              <el-option v-for="(item, index) in studentList" :key="index" :value="item.id">
                <span style="float: left">{{ item.name }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.idCardNumber }}</span>
              </el-option>
            </el-select> -->
            <template v-if="currentStudent">
              <span class="current_student" @click="clickSearchStudentDialog">
                <span class="text_style gl_mr_15">{{ currentStudent ? currentStudent.name: '' }}</span>
                <span class="text_style">{{ currentStudent ? currentStudent.idCardNumber : '' }}</span>
              </span>
            </template>
            <template v-else>
              <el-button style="width: 100%" size="small" @click="clickSearchStudentDialog">选择学员</el-button>
            </template>
          </el-form-item>
        </el-col>
        <el-col :xs="8" :sm="8" :md="12" :lg="6">
          <div v-if="importantRole['Club.Employee']" class="gl_pl_20">
            <el-button type="text" class="gl_ml_20" @click="jumpToAddStudent">去新增学员</el-button>
          </div>
        </el-col>
      </el-row>
      <el-divider content-position="left">经办信息</el-divider>
      <el-row>
        <el-col :xs="24" :sm="16" :md="12" :lg="6">
          <el-form-item label="经办日期" prop="date">
            <span>{{ today }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :xs="24" :sm="16" :md="12" :lg="6">
          <el-form-item label="经办人" prop="date">
            <span>{{ userName }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :xs="24" :sm="16" :md="12" :lg="6">
          <el-form-item label="销售员" prop="employeeId">
            <el-select v-model="vo.employeeId" style="width: 100%;" filterable placeholder="请选择销售员">
              <el-option v-for="(item, index) in employeeList" :key="index" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="left">选择购买卡种</el-divider>
      <el-row>
        <el-col :xs="24" :sm="16" :md="12" :lg="6">
          <el-form-item label="选择卡种" prop="membershipCardId">
            <el-select v-model="vo.membershipCardId" style="width: 100%;" filterable placeholder="选择购买卡种">
              <el-option v-for="(item, index) in cardList" :key="index" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <!-- 课时卡，包含课时和有效期，日期卡仅包含有效期 -->
          <template v-if="activeCard.id">
            <el-form-item v-if="activeCard.chargeTypeCode !== 'Date'" label="课时">
              <span>{{ activeCard.classPeriod }} 课时</span>
            </el-form-item>
            <el-form-item label="有效期">
              <span>{{ activeCard.effectivePeriod }} {{ activeCard.effectivePeriodType.name }}</span>
            </el-form-item>
            <el-form-item label="是否立即激活">
              <el-radio-group v-model="vo.isActiveNow">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </template>
        </el-col>
      </el-row>
      <!-- 物资赠品 -->
      <el-divider content-position="left">物资</el-divider>
      <el-row>
        <el-col :span="6">
          <el-form-item label="赠送商品" prop="giving">
            <el-radio-group v-model="vo.giving">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <template v-if="vo.giving">
            <el-form-item label="选择活动赠品" prop="gift">
              <el-select v-model="gift" style="width: 100%;" filterable placeholder="请选择活动赠品" @change="getinventories()">
                <el-option v-for="item in giftList" :key="item.value" :label="item.name" :value="item.inventories" />
              </el-select>
            </el-form-item>
            <el-form-item label="颜色" prop="color">
              <el-select v-model="vo.color" style="width: 100%;" filterable placeholder="请选择赠品颜色" @change="getsize(vo.color)">
                <el-option v-for="item in colorList" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="vo.color" label="型号" prop="type">
              <el-select v-model="vo.type" style="width: 100%;" filterable placeholder="请选择赠品型号">
                <el-option v-for="item in typeList" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
            <el-form-item label="数量" prop="num">
              <el-input v-model.number="vo.num" type="text" placeholder="请输入赠品数量" style="width:100%;" :controls="false" :precision="1" :min="1" :max="21474836" oninput="javascript:this.value=this.value.replace(/\D|^0/g,'')" />

            </el-form-item>
          </template>
        </el-col>
      </el-row>
    </el-form>
    <!-- 控制按钮 -->
    <el-row>
      <el-col class="control_btn_wrap" :span="24">
        <div class="control_btn">
          <el-button type="primary" size="small" :loading="submitLoading" @click="beforeSubmitRenewal">确认</el-button>
        </div>
      </el-col>
    </el-row>

    <el-dialog
      title="选择学员"
      :visible.sync="dialogVisible"
      :before-close="closeDialog"
      width="680px"
      class="gl_dialog_TitleLine gl_dl_footer"
    >
      <el-form :model="qo" label-width="80px" size="mini" @submit.native.prevent>
        <el-row :gutter="32">
          <el-col :span="12">
            <el-form-item label="学员姓名">
              <el-input v-model="qo.StudentName" clearable placeholder="请输入学员姓名" @keyup.enter.native="clickSearchStudent" @clear="clickSearchStudent" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-button type="primary" size="mini" @click="clickSearchStudent">筛选</el-button>
          </el-col>
        </el-row>
      </el-form>

      <el-table v-loading="tableLoading" :data="studentList" class="gl_mb_15 gl_table_noBorder" size="mini" style="width: 100%">
        <el-table-column prop="name" label="姓名" min-width="120" />
        <el-table-column label="性别" width="60" align="center">
          <template slot-scope="{row}">
            <span v-if="row.genderCode === 'M'">男</span>
            <span v-if="row.genderCode === 'W'">女</span>
          </template>
        </el-table-column>
        <el-table-column prop="idCardNumber" label="证件号码" min-width="150" />
        <el-table-column label="操作" width="80" align="center">
          <template slot-scope="{row}">
            <el-button size="mini" type="text" @click="chooseStudent(row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-row style="text-align: right;">
        <el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :pager-count="5"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="qo.MaxResultCount"
          :current-page="qo.Page"
          @size-change="changePageSize"
          @current-change="changePage"
        />
      </el-row>

    </el-dialog>
  </div>
</template>

<script>
import {
  api_GET_ClubStudent, // 学员列表
  api_GET_ClubEmployee, // 员工列表
  api_GET_ClubMembershipCards, // 卡种列表
  api_POST_ClubSalesCardRecordSubmitStudentSalesCardRecord, // 提交学生的卡片订单
  api_GET_ClubMaterial // 获取物资礼物
} from '@/extend/api/hallswaggerApi/app.js';

// import {
//   moneyYuanToFen,
//   moneyFenToYuan
// } from '@/lib/index.js';

import {
  SubmitStudentSalesCardRecordInput,
  Api_GET_ClubStudentQO,
  Api_GET_ClubMaterialQO
} from '@/lib/form/hall/swaggerForm.js';

export default {
  data () {
    return {
      pageLoading: false,
      studentId: '',
      studentList: [],
      employeeList: [],
      cardList: [],
      Api_GET_ClubMaterialQO: new Api_GET_ClubMaterialQO(),
      // ---
      vo: new SubmitStudentSalesCardRecordInput(),
      typeList: [],
      submitLoading: false,
      rules: {},
      giftList: [],
      colorList: [],
      gift: [],
      dialogVisible: false,
      qo: new Api_GET_ClubStudentQO(),
      tableData: [],
      total: 0,
      tableLoading: false,
      currentStudent: null
    };
  },
  computed: {
    // 今天 yyyy-mm-dd
    today () {
      const _date = new Date();
      const _y = _date.getFullYear();
      let _m = _date.getMonth() + 1;
      _m = _m < 10 ? '0' + _m : _m;
      let _d = _date.getDate();
      _d = _d < 10 ? '0' + _d : _d;
      return `${_y}-${_m}-${_d}`;
    },
    // 获取当前登录系统的用户名
    userName() {
      return this.$store.state.user.name;
    },
    // 获取当前登录系统的用户ID
    userRegisterId () {
      return this.$store.state.user.currentUserType.registerId;
    },
    // 关键权限
    importantRole () {
      // "Club.Employee" 人员管理权限，无此权限不能点击去新增学员
      // "Club.Income" 订单管理权限，无此权限不能点击查看订单详情
      const _roles = this.$store.state.user.roles;
      const _obj = {
        'Club.Employee': false,
        'Club.Income': false
      };
      for (let i = 0; i < _roles.length; i++) {
        const item = _roles[i];
        if (item in _obj) {
          _obj[item] = true;
        }
      }
      return _obj;
    },
    // 当前选中的卡
    activeCard () {
      return this.cardList.find(item => item.id === this.vo.membershipCardId) || {};
    }
    // 当前选中的赠品
    // activeGift () {
    //   return this.giftList.find(item => item.id === this.vo.giftId) || {};
    // }

  },
  watch: {
    vo: {
      deep: true,
      handler(val) {
        if (!val.giving) {
          this.$set(this.vo, 'color', '');
          this.$set(this.vo, 'type', '');
          this.$set(this.vo, 'num', '');
        }
      }
    }
  },
  created () {
    const _studentId = this.$route.params.studentId || '';
    this.studentId = _studentId; // 传入的id
    this.initParamasData();
    this.getEmployeeList();
    this.getCardList();
    this.getGift();
    this.$set(this.vo, 'giving', false);
  },
  methods: {
    // 从续费预警传过来得数据
    initParamasData () {
      if (this.studentId) {
        const { studentName, studentId } = this.$route.params;
        this.currentStudent = {
          name: studentName,
          id: studentId
        };
        this.vo.registerStudentId = studentId;
      }
    },
    closeDialog () {
      this.qo = new Api_GET_ClubStudentQO();
      this.qo.IsEnable = true;
      this.dialogVisible = false;
    },
    clickSearchStudentDialog () {
      this.qo = new Api_GET_ClubStudentQO();
      this.dialogVisible = true;
      this.apiGetStudent();
    },
    clickSearchStudent () {
      this.apiGetStudent();
    },
    // 获取销售员
    getEmployeeList () {
      this.apiGetEmployee({
        IsEnabled: true,
        EmployeeTypeCodes: ['Sale']
      });
    },
    // 获取卡种
    getCardList () {
      this.apiGetCards({
        IsEnable: true
      });
    },
    // 查询学员列表API
    apiGetStudent (page) {
      const _qo = JSON.parse(JSON.stringify(this.qo));
      _qo.Page = page || 1;
      this.qo.Page = _qo.Page;
      _qo.SkipCount = (_qo.Page - 1) * _qo.MaxResultCount;
      _qo.IsEnable = true;
      this.tableLoading = true;
      api_GET_ClubStudent(_qo)
        .then(
          res => {
            this.tableLoading = false;
            const _list = res.items || [];
            this.total = res.totalCount;
            this.studentList = _list;
            if (_list.length) {
              this.vo.registerStudentId = this.studentId;
            }
          }
        )
        .catch(
          error => {
            this.tableLoading = false;
            console.log('error: ', error);
          }
        );
    },
    chooseStudent (row) {
      this.vo.registerStudentId = row.id;
      this.currentStudent = row;
      this.closeDialog();
    },
    // 查询销售员列表API
    apiGetEmployee (qo) {
      api_GET_ClubEmployee(qo)
        .then(
          res => {
            this.employeeList = res.items || [];
          }
        )
        .catch(
          error => {
            console.log('error: ', error);
          }
        );
    },
    // 查询卡种列表API
    apiGetCards (qo) {
      api_GET_ClubMembershipCards(qo)
        .then(
          res => {
            this.cardList = res.items || [];
          }
        )
        .catch(
          error => {
            console.log('error: ', error);
          }
        );
    },
    beforeSubmitRenewal () {
      var hash = [];
      for (var i = 0; i < this.gift.length; i++) {
        if (this.vo.color === this.gift[i].color && this.vo.type === this.gift[i].size) {
          hash.push(this.gift[i]);
        }
      }
      console.log(hash);
      if (!this.vo.registerStudentId) {
        this.$message({
          message: `请选择学员！`,
          type: 'warning',
          showClose: true
        });
        return false;
      }
      if (!this.vo.employeeId) {
        this.$message({
          message: `请选择销售员！`,
          type: 'warning',
          showClose: true
        });
        return false;
      }
      if (!this.vo.membershipCardId) {
        this.$message({
          message: `请选择卡种！`,
          type: 'warning',
          showClose: true
        });
        return false;
      }
      if (this.vo.giving) {
        if (!this.gift) {
          this.$message({
            message: `请选择物资`,
            type: 'warning',
            showClose: true
          });
          return false;
        }
        if (!this.vo.color) {
          this.$message({
            message: `请选择颜色`,
            type: 'warning',
            showClose: true
          });
          return false;
        }
        if (!this.vo.type) {
          this.$message({
            message: `请选择型号`,
            type: 'warning',
            showClose: true
          });
          return false;
        }
        if (!this.vo.num) {
          this.$message({
            message: `请选择数量`,
            type: 'warning',
            showClose: true
          });
          return false;
        }
      }
      this.submitRenewal(hash);
    },
    // 确认报名续费
    submitRenewal (val) {
      console.log(val);
      this.submitLoading = true;
      this.vo.handlingDate = this.today;
      this.vo.isOnlinePayment = false;
      if (this.vo.giving) {
        this.vo.materials.push({});
        this.vo.materials[0].materialId = val[0].materialId;
        this.vo.materials[0].materialInventoryId = val[0].id;
        this.vo.materials[0].count = this.vo.num;
      }
      this.vo.isGiveMaterial = this.vo.giving;
      api_POST_ClubSalesCardRecordSubmitStudentSalesCardRecord(this.vo)
        .then(
          res => {
            this.renewalSuccess(res);
            this.submitLoading = false;
          }
        )
        .catch(
          error => {
            this.submitLoading = false;
            this.vo.materials = [];
            this.$message({
              message: `报名续费失败 ${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    renewalSuccess (val) {
      const _income = this.importantRole['Club.Income'];
      this.$confirm(`订单提交成功，订单编号：${val.orderNo}`, '提交成功', {
        confirmButtonText: _income ? '查看订单详情' : '确定',
        type: 'success',
        showCancelButton: false
      })
        .then(() => {
          if (_income) {
            this.$router.push({
              name: 'Income',
              query: {
                orderNo: val.orderNo
              }
            });
          }
        });
    },
    // 跳转至新增学员
    jumpToAddStudent () {
      if (this.$route.query.add) {
        console.log(this.$route.query.studentName);
        this.$router.push({ name: 'Student', query: { add: 'true',
          studentId: this.$route.query.studentId,
          studentName: this.$route.query.studentName,
          idCardTypeCode: this.$route.query.idCardTypeCode,
          idCardNumber: this.$route.query.idCardNumber }});
      } else {
        this.$router.push({
          name: 'Student',
          query: {
            add: 'true'
          }
        });
      }
    },
    // 获取物资
    getGift() {
      api_GET_ClubMaterial({ 'StatusCode': 'Enable', 'IncludeInventories': true, 'Sorting': 'creationTime DESC' }).then(res => {
        this.giftList = res.items;
      });
    },
    getinventories() {
      console.log(this.gift);
      this.colorList = this.getcolor(this.gift);
      this.$set(this.vo, 'color', '');
      this.$set(this.vo, 'type', '');
    },
    getcolor(val) {
      var hash = [];
      var obj = {};
      for (var i = 0; i < val.length; i++) {
        if (!obj[val[i].color]) {
          hash.push(val[i].color);
          obj[val[i].color] = true;
        }
      }
      return hash;
    },
    getsize(val) {
      this.$set(this.vo, 'type', '');
      var hash = [];
      for (var i = 0; i < this.gift.length; i++) {
        if (this.gift[i].color === val) {
          hash.push(this.gift[i].size);
        }
      }
      this.typeList = [... new Set(hash)];
    },
    // 分页
    changePage(page) {
      this.apiGetStudent(page);
    },
    changePageSize(pagesize) {
      this.qo.MaxResultCount = pagesize;
      this.apiGetStudent();
    }
  }
};
</script>

<style lang="scss" scoped>
  .control_btn_wrap {
    padding-top: 50px;
  }

  .control_btn {
    padding-left: 120px;
  }
  .current_student {
    cursor: pointer;
    word-break: break-all;
  }
  .text_style {
    padding-bottom: 2px;
    border-bottom: 1px solid #606266;
  }
</style>
